<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="800px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="formData"
                label-width="120px"
                :rules="formRules"
            >
                <el-form-item label="商品名称" prop="title">
                    <el-input
                        v-model="formData.title"
                        placeholder="请输入商品名称"
                        maxlength="50"
                        show-word-limit
                    />
                </el-form-item>
                <el-form-item label="商品类型" prop="cid">
                    <el-select
                        v-model="formData.cid"
                        placeholder="请选择商品类型"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in shopTypeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="商品价格" prop="price">
                    <el-input-number
                        v-model="formData.price"
                        :min="0"
                        :precision="2"
                        :step="0.01"
                        placeholder="请输入商品价格"
                        style="width: 200px"
                    />
                    <span class="ml-2 text-tx-secondary">元</span>
                </el-form-item>
                <el-form-item label="图片" prop="image">
                    <material-picker
                        v-model="formData.image"
                        :limit="99"
                        type="image"
                    />
                </el-form-item>
                <el-form-item label="商品库存" prop="stock">
                    <el-input-number
                        v-model="formData.stock"
                        :controls="false"
                        :min="0"
                        :precision="0"
                        placeholder="请输入商品库存"
                        style="width: 200px"
                    />
                    <span class="ml-2 text-tx-secondary">件</span>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number
                        v-model="formData.sort"
                        :min="0"
                        :max="9999"
                        placeholder="请输入排序值"
                        style="width: 200px"
                    />
                    <!-- <div class="form-tips">数值越大越靠前</div> -->
                </el-form-item>
                <el-form-item label="商品描述" prop="content">
                    <!-- <el-input
                        v-model="formData.content"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入商品描述"
                        maxlength="500"
                        show-word-limit
                    /> -->
                    <editor v-model="formData.content" height="400px" />
                </el-form-item>
                
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { apiShopAdd, apiShopEdit, apiShopDetail, apiShopCategoryLists } from '@/api/shop'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import Editor from '@/components/editor/index.vue'
interface Props {
    dictData?: Record<string, any[]>
}

defineProps<Props>()

const emit = defineEmits<{
    success: []
    close: []
}>()

const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑商品' : '新增商品'
})

// 表单数据
const formData = ref<Record<string, any>>({
    title: '',
    cid: '',
    price: 0,
    image: [],
    sort: 0,
    content: '',
    stock: 0,
})

// 表单验证
const formRules = reactive({
    title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    cid: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
    price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
    stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
    image: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
})

// 商品类型列表
const shopTypeList = ref<any[]>([])

// 获取商品类型列表
const getShopTypeList = async () => {
    try {
        const data = await apiShopCategoryLists({
            page: 1,
            limit: 999
        })
        shopTypeList.value = data.lists
    } catch (error) {
        console.error('获取商品类型失败:', error)
    }
}

const editId = ref()
// 获取详情
const setFormData = async (data: Record<string, any>) => {
    if(data.id){
        editId.value = data.id
    }
    for (const key in formData.value) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            if(key == 'image'){
                formData.value[key] = data[key].split(',')
            }else{
                formData.value[key] = data[key]
            }
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiShopDetail({
        id: row.id
    })
    setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData.value }
    if(formData.value.image.length > 0){
        data.image = formData.value.image.join(',')
    }
    mode.value == 'edit' ? await apiShopEdit({
        ...data,
        id: editId.value
    }) : await apiShopAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

// 打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

// 初始化
onMounted(() => {
    getShopTypeList()
})

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style scoped>
.form-tips {
    color: var(--el-text-color-regular);
    font-size: 12px;
    line-height: 1.5;
    margin-top: 4px;
}
</style>